#include "stdafx.h"
#include "PhysicsController.h"
#include "PhysicsSystem.h"

PhysicsController::PhysicsController(Model *model) {
	setModel(model);
}

PhysicsController::~PhysicsController() {
	delete m_goMap;
	m_goMap = NULL;
}

bool PhysicsController::update(float deltaTime) {
	m_goMap = m_currentModel->getGoMap();

	std::map<unsigned int, GameObject*>::iterator i;
	for( i = m_goMap->begin(); i != m_goMap->end(); i++ )  {
		GameObject *go = (*i).second;
		PhysicsComponent* pc = go->getPhysicsComponent();
		
		if( pc ) {
			if( pc->isFresh() ) {
				// If the game object is new, add it to the physics world
				pc->addToWorld( PhysicsSystem::getInstance() );
			}

			// Sets updated position and orientation for the game object
			go->setPosition( pc->getPosition() );
			
			if(pc->shouldUpdateOrientation()) {
				go->setOrientation(pc->getOrientation());
			}

			// Updates the gravitational pull towards the center of the planetoid (At the moment towards origo)
			pc->setGravityTowards( deltaTime, Ogre::Vector3(0,0,0) );
		}
	}
	
	return true;
}